using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using PowerManage.API.Auth;

namespace PowerManage.API.Extensions;

/// <summary>
/// JWT相关扩展
/// </summary>
public static class JwtExtension
{
    /// <summary>
    /// JWT、认证相关
    /// </summary>
    /// <param name="builder"></param>
    public static void AddPowerManageJwt(this WebApplicationBuilder builder)
    {
        //添加jwt验证
        var jwtBearer = builder.Configuration.GetSection(AppSettings.Authentication).GetSection(AppSettings.JwtBearer);
        builder.Services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //设置默认的身份验证方案
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //设置默认的挑战方案
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; //设置默认的方案
        }).AddJwtBearer(options =>
        {
            //设置 JWT 令牌验证参数
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true, //启用发行者验证 确保令牌的发行者与配置的发行者一致 防止伪造、一致性 开发阶段可以不开启
                ValidIssuer = jwtBearer[AppSettings.Issuer], //设置有效的发行者
                ValidateAudience = true, //启用受众验证 确保令牌的受众与配置的受众一致
                ValidAudience = jwtBearer[AppSettings.Audience], //设置有效的受众
                ValidateIssuerSigningKey = true, //启用签名密钥验证 确保令牌的签名密钥与配置的签名密钥一致
                IssuerSigningKey =
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtBearer[AppSettings.SecurityKey] ?? string.Empty)), //设置签名密钥
                ValidateLifetime = true, //是否验证失效时间
                ClockSkew = TimeSpan.FromSeconds(5) //ClockSkew 是一个时间间隔，用于处理不同服务器之间的时间差异 偏差秒数：防止客户端与服务器时间偏差 5s 
            };
        });
    }
}